<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="应用名称" prop="appName">
        <el-input
          v-model="queryParams.appName"
          placeholder="请输入应用名称"
          clearable
          maxlength="200"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="应用平台" prop="appPlatform">
        <el-select v-model="queryParams.appPlatform" placeholder="请选择应用平台">
          <el-option
            v-for="dict in dict.type.app_name_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="appStatus">
        <el-select v-model="queryParams.appStatus" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_enable_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="授权模式" prop="grantTypes">
        <el-select v-model="queryParams.grantTypes" placeholder="请选择授权模式" clearable>
          <el-option
            v-for="dict in dict.type.grant_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
     
      <el-form-item label="是否需要授权" prop="isGrant">
        <el-select v-model="queryParams.isGrant" placeholder="请选择是否需要授权" clearable>
          <el-option
            v-for="dict in dict.type.sys_grant_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:appinfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:appinfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:appinfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="refreshApp"
        >刷新缓存</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="tables" v-loading="loading" :data="appinfoList" @selection-change="handleSelectionChange" :default-sort="defaultSort" @sort-change="handleSortChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="应用Id" align="center" prop="appId" v-if="true"/>
      <el-table-column label="应用秘钥" align="center" prop="appSecret" />
      <el-table-column label="回调地址" align="center" prop="appRedirectUri" />
      <el-table-column label="应用名称" align="center" prop="appName" />
      <el-table-column label="应用平台" align="center" prop="appPlatform" width="140">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.app_name_type" :value="scope.row.appPlatform"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="appStatus">
       <!-- <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_enable_status" :value="scope.row.appStatus"/>
        </template>-->
        <template slot-scope="scope">
              <el-switch
                v-model="scope.row.appStatus"
                active-value="1"
                inactive-value="0"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="授权模式" align="center" prop="grantTypes" width="140"> 
        <template slot-scope="scope">
          <dict-tag :options="dict.type.grant_type" :value="scope.row.grantTypes"/>
        </template>
      </el-table-column>
      <el-table-column label="申请人邮箱" align="center" prop="email" />
      <el-table-column label="是否需要授权" align="center" prop="isGrant"  width="140">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_grant_status" :value="scope.row.isGrant"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createDate" width="180" sortable="custom" :sort-orders="['descending', 'ascending']">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后更新时间" align="center" prop="lastUpdateDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastUpdateDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:appinfo:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:appinfo:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改应用注册对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="回调地址" prop="appRedirectUri">
          <el-input v-model="form.appRedirectUri"  placeholder="请输入回调地址" maxlength="200"/>
        </el-form-item>
        <el-form-item label="应用名称" prop="appName">
          <el-input v-model="form.appName" placeholder="请输入应用名称" maxlength="100"/>
        </el-form-item>
         <el-form-item label="应用平台" prop="appPlatform">
          <el-select v-model="form.appPlatform" placeholder="请选择应用平台" style="width:100%" clearable>
            <el-option
              v-for="dict in dict.type.app_name_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="appStatus">
          <el-select v-model="form.appStatus" placeholder="请选择状态" style="width:100%" clearable>
            <el-option
              v-for="dict in dict.type.sys_enable_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="授权模式" prop="grantTypes">
          <el-select v-model="form.grantTypes" placeholder="请选择授权模式" style="width:100%" clearable>
            <el-option
              v-for="dict in dict.type.grant_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否需要授权" prop="isGrant">
          <el-select v-model="form.isGrant" placeholder="请选择是否需要授权" style="width:100%" clearable>
            <el-option
              v-for="dict in dict.type.sys_grant_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申请人邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入申请人邮箱" maxlength="50"/>
        </el-form-item>
        <el-form-item label="应用简介" prop="appDesc">
          <el-input v-model="form.appDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAppinfo, getAppinfo, delAppinfo, addAppinfo, updateAppinfo, refreshAppInfo, changeAppInfoStatus } from "@/api/system/appinfo";

export default {
  name: "Appinfo",
  dicts: ['grant_type', 'app_name_type', 'sys_del_flag', 'sys_enable_status', 'sys_grant_status'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 应用注册表格数据
      appinfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 默认排序
      defaultSort: {prop: 'createDate', order: 'descending'},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        appSecret: undefined,
        appRedirectUri: undefined,
        appName: undefined,
        appPlatform: undefined,
        appDesc: undefined,
        appPic: undefined,
        appStatus: undefined,
        grantTypes: undefined,
        email: undefined,
        isGrant: undefined,
        createDate: undefined,
        lastUpdateDate: undefined,
        lastUpdateBy: undefined,
        deleteFlag: undefined,
        orderByColumn: 'createDate',
        isAsc: 'descending'
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        appRedirectUri: [
          { required: true, message: "回调地址不能为空", trigger: "blur" },
          {
            pattern: /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/,
            message: "回调地址格式不正确",
            trigger: "blur"
          }
        ],
        appName: [
          { required: true, message: "应用名称不能为空", trigger: "blur" }
        ],
        appPlatform: [
          { required: true, message: "应用平台不能为空", trigger: "blur" }
        ],
        appStatus: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],
        grantTypes: [
          { required: true, message: "授权模式不能为空", trigger: "blur" }
        ],
        email: [
          { required: true, message: "申请人邮箱不能为空", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }
        ],
        isGrant: [
          { required: true, message: "是否需要授权不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询应用注册列表 */
    getList() {
      this.loading = true;
      listAppinfo(this.queryParams).then(response => {
        this.appinfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 应用状态修改
    handleStatusChange(row) {
      let text = row.appStatus === "0" ? "停用" : "启用";
      this.$modal.confirm('确认要"' + text + '""' + row.appName + '"应用吗？').then(function() {
        return changeAppInfoStatus(row.appId, row.appStatus);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
        this.getList();
      }).catch(function() {
        row.appStatus = row.appStatus === "1" ? "0" : "1";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        appId: undefined,
        appSecret: undefined,
        appRedirectUri: undefined,
        appName: undefined,
        appPlatform: "APP",
        appDesc: undefined,
        appPic: undefined,
        appStatus: "0",
        grantTypes: "authorization code",
        email: undefined,
        isGrant: "0",
        createDate: undefined,
        createBy: undefined,
        lastUpdateDate: undefined,
        lastUpdateBy: undefined,
        deleteFlag: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.$refs.tables.sort(this.defaultSort.prop, this.defaultSort.order);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.appId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加应用注册";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const appId = row.appId || this.ids
      getAppinfo(appId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改应用注册";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.appId != null) {
            updateAppinfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addAppinfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const appIds = row.appId || this.ids;
      this.$modal.confirm('是否确认删除应用注册编号为"' + appIds + '"的数据项？').then(() => {
        this.loading = true;
        return delAppinfo(appIds);
      }).then(() => {
        this.loading = false;
        this.handleQuery();
        this.$modal.msgSuccess("删除成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/appinfo/export', {
        ...this.queryParams
      }, `appinfo_${new Date().getTime()}.xlsx`)
    },
    /** 刷新缓存按钮 */
    refreshApp() {
      refreshAppInfo().then(response => {
        if(response.code === 200){
          this.$modal.msgSuccess("刷新缓存成功");
        }else{
          this.$modal.msgSuccess("刷新缓存失败");
        } 
      });
    }
  }
};
</script>
